package fbcache

import (
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis"
	"longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/imsdk"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	"longmen/server/internal/rpc/tencentim/messages/sports"
	"longmen/server/internal/services/nami/services/sports/basketball/bbcache"
	"sync"
)

type NatsStats struct {
	MatchId int `json:"match_id"`
	Type    int `json:"type"`
	Home    int `json:"home"`
	Away    int `json:"away"`
}

type StatsCache struct {
	rds redis.UniversalClient
}

var statsCache *StatsCache
var statsCacheOnce sync.Once

func NewStatsCache() *StatsCache {
	statsCacheOnce.Do(func() {
		statsCache = &StatsCache{
			rds: global.GetRds(),
		}
	})
	return statsCache
}

// 生成足球即时比分key
func (s *StatsCache) genStatsKey(matchId int) string {
	return fmt.Sprintf("match_live:football_stats:%d", matchId)
}

func (s *StatsCache) PublishStats(records []NatsStats) error {
	dataMap := make(map[int][]NatsStats)
	for _, record := range records {
		dataMap[record.MatchId] = append(dataMap[record.MatchId], record)
	}
	pp := s.rds.Pipeline()
	for id, stats := range dataMap {
		newMsg := sports.FootballStatsMessage{
			SentMessageStruct: messages2.SentMessageStruct{Type: messages2.StatsLiveMessageType},
			Stats:             stats,
		}
		marshal, _ := json.Marshal(newMsg)

		pp.Set(s.genStatsKey(id), string(marshal), bbcache.CacheExpire)
		imsdk.GetSdk().BroadcastInterface(id, newMsg, 0)
	}

	_, err := pp.Exec()
	if err != nil {
		global.Log.Errorf("Pipeline run error: %v", err)
	}

	return nil
}

// GetStatsCache 获取缓存
func (s *StatsCache) GetStatsCache(matchId int) string {
	result, err := s.rds.Get(s.genStatsKey(matchId)).Result()
	if err != nil {
		return ""
	}
	return result
}
